package com.hbnu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbnu.mapper.UserMapper;
import com.hbnu.pojo.OTD.LoginRequest;
import com.hbnu.pojo.OTD.LoginResponse;
import com.hbnu.pojo.OTD.LoginResponseData;
import com.hbnu.pojo.User;
import com.hbnu.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class LoginController {
    @Autowired
    private UserMapper userMapper;

    //登录验证
    @PostMapping("/login")
    public LoginResponse login(@RequestBody LoginRequest request){

        //查找用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",request.getUsername());

        User user = userMapper.selectOne(queryWrapper);
        //验证用户
        if (user == null){
            return new LoginResponse(false,"用户名不存在",null);
        }
        //验证密码
        if (!user.getPassword().equals(request.getPassword())){
            return new LoginResponse(false,"密码错误", null);
        }
        //生成token
        String token = JwtUtil.generateToken(user.getUsername());

        // 用新的数据结构封装返回值
        LoginResponseData data = new LoginResponseData(token, user.getUsername() , user.getImage(), user.getId());

        return new LoginResponse(true, "登录成功", data);
    }

}